package edu.gxmzu.task.controller;

import edu.gxmzu.task.entity.TaskBody;
import edu.gxmzu.task.params.NewTaskParam;
import edu.gxmzu.task.service.TaskService;
import edu.gxmzu.task.utils.JWTUtil;
import edu.gxmzu.task.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

@RestController
@Slf4j
@Tag(name = "用户任务模块")
public class TaskController {

    @Resource
    private TaskService taskService;

    @PostMapping("/tasks")
    @Operation(summary = "删除任务（批量）")
    public Result deleteTask(@RequestBody TaskBody taskBody) {

        if(taskBody.getTaskIds() == null || taskBody.getTaskIds().isEmpty()) {
            return Result.fail("任务id不能为空");
        }
        int result = taskService.deleteTask(taskBody.getTaskIds());
        if (result > 0) {
            return Result.ok("任务删除成功");
        } else {
            return Result.fail("任务删除失败");
        }
    }

    @Operation(summary = "普通用户新建任务", description = "此处为准<br>" +
            "请求数据类型：form-data<br>"+
            "{" +
            "<br/>title: 任务标题（必填，用于描述任务的主要内容）<br/>" +
            "<br/>content: 任务内容（必填，详细的任务描述或执行步骤）<br/>" +
            "<br/>require: 任务要求（选填，对任务执行者的特殊要求或说明）<br/>" +
            "<br/>endTime: 截止时间，传时间戳（选填，任务应完成的日期和时间）<br/>" +
            "<br/>file: 附件（选填）<br/>" +
            "}")
    @PostMapping("/newTask")
    public Result newTask(@RequestHeader(value = "jwtToken") @Schema(description = "请求头携带") String token,
                           @ModelAttribute NewTaskParam workParam
    ) {

        String userId= JWTUtil.getUserIdFromToken(token);
        try{
            return taskService.newTask(workParam,userId);
        }catch (Exception e){
            return Result.badRequest("新建任务失败");
        }
    }


    /**
     * 通用文件下载方法
     * @param fileName 文件名
     * @param response HTTP响应对象
     */
    @Operation(summary = "根据文件名获取文件",description = "请求格式如：fileName:123.txt")
    @GetMapping("/downloadFile")
    public void downloadFile(String fileName, HttpServletResponse response) {
        try {
            String projectPath = System.getProperty("user.dir");
            String filesPath = projectPath + File.separator + "WEB-INF" + File.separator + "files";
            String filesRealPath = filesPath + File.separator;
            // 获取文件的完整路径
            String filePath = filesRealPath + fileName;
            log.info(filePath);
            File file = new File(filePath);

            if (!file.exists()) {
                throw new RuntimeException("文件不存在");
            }
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");

            // 处理文件名中文乱码
            String downloadFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + downloadFileName);
            // 创建输入流
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            // 创建输出流
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) != -1) {
                bos.write(buff, 0, len);
            }

            // 关闭资源
            bos.flush();
            bos.close();
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件下载失败");
        }
    }

}
